<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link 
            href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" 
            rel="stylesheet">
        <link rel="stylesheet" href="css/appctl.css" media="screen">

        <!---->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>

        <script>
            var dojoConfig = {
                async: true
            };
        </script>
        <!--script src="js/slibs/dojo/dojo.js"></script-->
        <script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js"></script>

        <script type="text/javascript">
            require([
                "dojo/_base/lang",
                "dojo/_base/fx",
                "dojo/request/notify",
                "dojo/store/JsonRest",
                "dojo/store/Memory",
                "dojo/store/Cache",
                "dojo/query",
                "dojo/dom-construct",
                "dojo/fx",
                "dojo/on",
                "dojo/dom-form",
                "dojo/request",
                "dojo/NodeList-manipulate",
                "dojo/NodeList-dom",
                "dojo/domReady!"
            ], function(lang,
                    baseFx,
                    notify,
                    JsonRest,
                    Memory,
                    Cache,
                    query,
                    domConstruct,
                    fx,
                    on,
                    domForm,
                    request) {


                function Model() {
                    var jsonRest = new JsonRest({target: "rst/user/"});
                    var cacheStore = new Memory({});
                    var userStore = new Cache(jsonRest, cacheStore);

                    var callbacks = {};

                    function userJsonRewrite(srvUser) {
                        return jsonRewrite(srvUser, "user");
                    }

                    function jsonRewrite(obj, prop) {
                        return obj[prop] ? obj[prop] : obj;
                    }

                    function fireCallbacks(callbacksArray, args) {
                        if (callbacksArray && callbacksArray.length) {
                            for (var i = 0; i < callbacksArray.length; i++) {
                                callbacksArray[i](args);
                            }
                        }
                    }

                    return {
                        registerCallback: function(event, callback) {
                            console.log(callbacks[event]);
                            callbacks[event] = callbacks[event] ? callbacks[event] : [];
                            callbacks[event].push(callback);
                        },
                        get: function(id) {
                            userStore.get(id).then(function(srvUser) {
                                console.log("get in Controller(" + id + ")=" + srvUser);
                                srvUser = userJsonRewrite(
                                        srvUser
                                        );
                                var callbacksArray = callbacks['get'];
                                fireCallbacks(callbacksArray, jsonRewrite(srvUser, 'user'));
                            });

                        },
                        query: function(queryObj) {
                            for (var p in queryObj) {
                                if (!queryObj[p]) {//delete empty query params
                                    delete queryObj[p];
                                }
                            }
                            fireCallbacks(callbacks['beforeQuery'], queryObj);
                            return userStore.query(queryObj)
                                    .then(function(srvUsers) {
                                        fireCallbacks(callbacks['query'], userJsonRewrite(srvUsers));
                                    });


                        },
                        mailTo: function(queryObj) {
                            for (var p in queryObj) {
                                if (!queryObj[p]) {//delete empty query params
                                    delete queryObj[p];
                                }
                            }
                            fireCallbacks(callbacks['beforeMail'], queryObj);
                            return  request.post('rst/mail', {
                                data: queryObj
                            }).then(function(val) {
                                console.log('mail returned: ' + val);
                                fireCallbacks(callbacks['sendMail'], val);
                            });
                        }
                    };
                }

                function View() {

                    function makeRow(user, node) {
                        var clz = user.lastName ? '' : 'warning';
                        clz = (user.enabled == 'y') ? clz : 'error';
                        clz = clz + ' userListRow';
                        // clz=clz.trim();
                        domConstruct.create("tr", {class: clz,
                            "data-idUser": user.idUser,
                            innerHTML: makeCell(user.idUser) +
                                    makeCell(user.login) +
                                    makeCell(user.lastName) +
                                    makeCell(user.userGroup) +
                                    makeCell(user.enabled)},
                        node);
                    }

                    function makeCell(text) {
                        text ? '' : text = 'не указано';
                        //console.log(clz);
                        return "<td>" + text + "</td>";
                    }


                    function getSelectedOptionValue(select) {
                        return select.options[select.selectedIndex].value;
                    }

                    return {
                        makeUsersTable: function(users) {
                            var tableBodyNode = query("#usersGrid tbody")[0];//returns NodeList, actually array with dojo extensions
                            tableBodyNode.innerHTML = '';
                            if (users && users.length) {
                                for (var i = 0; i < users.length; i++) {
                                    makeRow(users[i], tableBodyNode);
                                }
                            }
                        },
                        makeUserInfo: function(user) {
                            function getEmpty(arg) {
                                return arg ? ' ' + arg : '';
                            }
                            function getEnabled(arg) {
                                return arg == 'y' ? true : false;
                            }

                            /*
                             enabled: "y"
                             firstName: null id: "48" idUser: 48 lastName: "Апрохин" login: "aprohin" pass:
                             "***" secondName: null userGroup: "speed-512" */
                            var a = query("#userInfoForm input[name=userAccount]");
                            //http://dojotoolkit.org/api/?qs=1.9/dojo/NodeList
                            query("#userInfoForm input[name=idUser]")
                                    .val(user.idUser)
                                    .attr("value", user.idUser);

                            query("#userInfoForm input[name=userAccount]")
                                    .val((getEmpty(user.lastName) +
                                            getEmpty(user.firstName) +
                                            getEmpty(user.secondName)).trim());

                            query("#userInfoForm input[name=userLogin]").val(
                                    getEmpty(user.login));

                            query("#userInfoForm input[name=userGroup]").val(
                                    getEmpty(user.userGroup));

                            query("#userInfoForm input[name=userEnabled]")
                                    .val(getEnabled(user.enabled))
                                    .attr("checked", getEnabled(user.enabled));

                            console.log(user);
                        },
                        makeFilterTable: function(fire, event) {
                            event.preventDefault();
                            console.log("--makefiltertable");
                            console.log(event);
                            console.log(domForm.toObject("userListFilterForm"));
                            fire(domForm.toObject("userListFilterForm"));
                        },
                        showUserInfo: function(fire, event) {
                            event.preventDefault();
                            console.log("--showUserInfo");
                            console.log(event);
                            fx.chain([
                                fx.wipeOut({node: 'usersGrid'}),
                                fx.wipeOut({node: 'userListFilterForm'}),
                                fx.wipeIn({node: 'backToList'}),
                                fx.wipeIn({node: 'userInfoForm'}),
                                baseFx.fadeIn({node: 'backToList'}),
                                baseFx.fadeIn({node: 'userInfoForm'})
                            ]).play();
                            console.log(this.dataset);// <tr> data-* attributes
                            fire(this.dataset.iduser);
                        },
                        backToList: function(fire, event) {
                            event.preventDefault();
                            console.log("--backToList");
                            console.log(event);
                            var mailBtn = query("#sendUserInfo")[0];//кнопка отправки почты
                            mailBtn.disabled = false;
                            mailBtn.innerHTML = 'Send';
                            mailBtn.value = 'Send';

                            fx.chain([
                                fx.wipeOut({node: 'backToList'}),
                                fx.wipeOut({node: 'userInfoForm'}),
                                fx.wipeIn({node: 'usersGrid'}),
                                fx.wipeIn({node: 'userListFilterForm'})
                            ]).play();

                            //makeFilterTable(fire,event);
                        },
                        sendingMail: function(fire, event) {
                            event.preventDefault();
                            console.log("--sendingMail");
                            console.log(event);
                            console.log(domForm.toObject("userInfoForm"));
                            fire(domForm.toObject("userInfoForm"));
                        },
                        toggleBtn: function(btn, enbl, text, event) {
                            console.log(arguments);
                            btn.disabled = enbl;
                            btn.innerHTML = text;
                            btn.value = text;
                        },
                        showError: function(error) {

                            fx.chain([
                                fx.wipeOut({node: 'usersGrid'}),
                                fx.wipeOut({node: 'userListFilterForm'}),
                                fx.wipeOut({node: 'userInfoForm'}),
                                fx.wipeOut({node: 'backToList'}),
                                fx.wipeIn({node: 'errorAlert'}),
                                baseFx.fadeIn({node: 'errorAlert'})
                            ]).play();

                            var ed = query("#errorAlert pre")[0];
                            ed.innerHTML = "Message:" + error.message;
                            // alert(error);
                        }
                    };
                }

                fx.wipeOut({node: 'errorAlert'}).play(); //dipslay:none для прозрачного диалога
                fx.wipeOut({node: 'backToList'}).play();
                fx.wipeOut({node: 'userInfoForm'}).play();


                var model = new Model();
                var vw = new View();

                notify("error", vw.showError);

                model.registerCallback('query', vw.makeUsersTable);
                model.registerCallback('query', function() { //  bind|rebind handlers on rows
                    var rows = query("#usersGrid tr");
                    on(rows, "click", lang.partial(vw.showUserInfo, model.get));
                });

                model.registerCallback('get', vw.makeUserInfo);

                model.query().then(function(srvUsers) {//bind ui after first call user list
                    var filterBtn = query("#userListFilterSubmit")[0]; //кнопка apply filters
                    var filterEnSelect = query("#userListFilterForm [name=enabled]")[0];//селектор включенных/отключенных аккаунтов
                    var filterGrpSelect = query("#userListFilterForm [name=userGroup]")[0];//селектор групп(скоростей)

                    var mailBtn = query("#sendUserInfo")[0];//кнопка отправки почты

                    var backToListLink = query("#backToList");

                    on(backToListLink, "click", lang.partial(vw.backToList, model.query));

                    model.registerCallback('beforeQuery',
                            lang.partial(vw.toggleBtn, filterBtn, true, 'Loading...'));
                    model.registerCallback('query',
                            lang.partial(vw.toggleBtn, filterBtn, true, 'Done'));
                    on(filterBtn, "click",
                            lang.partial(vw.makeFilterTable, model.query));
                    on(filterEnSelect, "change",
                            lang.partial(vw.toggleBtn, filterBtn, false, 'Apply Filters'));

                    on(filterGrpSelect, "change",
                            lang.partial(vw.toggleBtn, filterBtn, false, 'Apply Filters'));


                    //почта
                    model.registerCallback('beforeMail',
                            lang.partial(vw.toggleBtn, mailBtn, true, 'Sending...'));
                    model.registerCallback('sendMail',
                            lang.partial(vw.toggleBtn, mailBtn, true, 'Done'));

                    on(mailBtn, "click",
                            lang.partial(vw.sendingMail, model.mailTo));
                }); //first call
            });

        </script>
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="navbar-inner">
                <div class="container-fluid">
                    <a class="brand" href="#">User list</a>
                </div>
            </div>
        </div>

        <div class="container-fluid">
            <div class="row-fluid">

                <!--=========left column=========================-->
                <div class="span2">
                    <form id="userListFilterForm">
                        <fieldset>
                            <legend>Filters</legend>
                            <span class="help-block">select, if need, the appropriate filters and apply them</span>
                            <label>Enabled user ?</label>
                            <select title=" Enabled User ?" 
                                    name="enabled">
                                <option value="" selected>Any</option>
                                <option value="y">Yes</option>
                                <option value="n">No</option>
                            </select>
                            <label>User group</label>
                            <select title=" User group ?" 
                                    name="userGroup">
                                <option value="" selected>Any</option>
                                <option value="speed-1000">speed-1000</option>
                                <option value="speed-512">speed-512</option>
                                <option value="speed-256">speed-256</option>
                                <option value="speed-128">speed-128</option>
                                <option value="speed-64">speed-64</option>
                                <option value="speed-32">speed-32</option>
                            </select>
                            <button id="userListFilterSubmit" 
                                    name="userListFilterSubmit"
                                    class="btn btn-primary"
                                    type="button"
                                    data-loading-text="Loading...">Apply Filters</button>
                        </fieldset>
                    </form>
                    <div class="faceLegend" id="backToList">
                        <a href="#">&lt;- Back to Users list</a>
                    </div>
                </div> <!--//end left column-->

                <div class="span9">
                    <div id="errorAlert" class="alert alert-error">
                        <p>
                            <strong>К сожалению произошла ошибка,
                                пожалуйста скопируйте текст сообщения и вышлите разработчику
                            </strong>
                        </p>
                        <pre><!--ajax here--></pre>
                    </div>
                    <!--p>Send user info via email</p-->
                    <form class="form-horizontal" id="userInfoForm">
                        <div class="faceLegend">
                            <p style="margin: 0px"> User Info</p>
                        </div>
                        <input type="hidden" 
                               name="idUser" >

                        <div class="control-group">
                            <label for="userAccount" class="control-label">Account</label>
                            <div class="controls">
                                <input type="text" readonly
                                       name="userAccount" placeholder="Account info" >
                            </div>
                        </div>

                        <div class="control-group">
                            <label for="userLogin" class="control-label">Login</label>
                            <div class="controls">
                                <input type="text" readonly
                                       name="userLogin" placeholder="login" >
                            </div>
                        </div>

                        <div class="control-group">
                            <label for="userGroup" 
                                   class="control-label">Group</label>
                            <div class="controls">
                                <input type="text" readonly
                                       name="userGroup" placeholder="User Group">
                            </div>
                        </div>
                        <div class="control-group">
                            <label for="userPassword" 
                                   class="control-label">Password</label>
                            <div class="controls">
                                <input type="password" readonly
                                       name="userPassword" placeholder="*****">
                            </div>
                        </div>

                        <div class="control-group">
                            <label for="userGroup" 
                                   class="control-label">Enabled?</label>
                            <div class="controls">
                                <input type="checkbox" disabled
                                       name="userEnabled">
                            </div>
                        </div>

                        <div class="control-group">
                            <label for="sendUserInfo" 
                                   class="control-label">Send User Info to admin email</label>
                            <div class="controls">
                                <button id="sendUserInfo" 
                                        name="senUserInfo"
                                        class="btn btn-primary"
                                        type="button"
                                        data-loading-text="Sending...">Send</button>
                            </div>
                        </div>


                    </form>
                    <!--p>ADSL and DialUp users list below:</p-->
                    <table id="usersGrid" class="table table-hover">
                        <thead>
                            <tr>
                                <th>Id</th>
                                <th>Login</th>
                                <th>User</th>
                                <th>Group</th>
                                <th>Enabled?</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!--ajax here-->
                        </tbody>
                    </table>
                </div>
            </div>
            <hr/>
            <footer>
                <span>2013 @IT Department</span>
                <a href="#">$HeadURL$</a>
            </footer>
        </div>


    </body>
</html>